//knowledge页面的input框获取焦点；
inputFn($('.knowledgeBtn_knowledge .searchBox'));
$('.knowledgeBtn_knowledge .content form').on('click', 'input[type="submit"]', function() {
    var $el = $('.knowledgeBtn_knowledge .content input[type="text"]');
    if ($el.val() != $el.attr('data-txt')) {
        var keywords = $el.val();
        // 分级标题
        var str2 = " ",
            $el2 = $('#learnKnow_rightCont_titlebar');
        $el2.empty();
        // 分级标题数据插入结构中
        str2 += '<span class="on">&ensp;知识搜索&ensp;&gt;&ensp;搜索结果</span>';
        $el2.html(str2);
        rightListFn(null, keywords, 1);
    }
});
(function(){
	RequestGTMC('listKnowledgeByName',{
		kngCategoryId:'316294497424680043'
	},
	function(data){
		console.log("获取返回列表：成功");
		console.log("获取返回列表",data)
	},
	function(){
		console.log("获取返回列表：失败");
	},
	function(){
		console.log("获取返回列表：完成");
	})
})();
// 本页面数据加载
(function() {
    var CommonSucceed = AjaxComplete(2);
    // 左侧导航栏
    RequestGTMC("listKngCategory", {},
        function(data) {
            // 把data 数据转为对象dataObj中并插入左侧导航栏；
            var dataObj = new Object();
            console.log("左侧菜单 调用成功");
            console.log(data);
            // data数据转为dataObj对象
            if (data.length !== 0) {
                // 左侧导航一级菜单；
                var data1 = [];
                // 左侧导航一级菜单的第一部分二级菜单；
                var DataFirst = [];
                // 左侧导航一级菜单的第二部分二级菜单；
                var DataSecond = [];
                for (var j = 0; j < data.length; j++) {
                    var oData = data[j];
                    var nodeData = oData.treenodePath.substr(1, data[j].treenodePath.length - 2).split('/');
                    var n = nodeData.length;
                    if (n >= 1) {
                        if (n == 1) {
                            data1.push(oData);
                            for (var i = 0; i < data1.length; i++) {
                                dataObj[data1[i].name] = new Array();
                            }
                        }
                        if (n >= 2) {
                            if (nodeData[0] == data1[0].id) {
                                if (n == 2) {
                                    DataFirst.push(oData);
                                    for (var m = 0; m < DataFirst.length; m++) {
                                        if (!dataObj[data1[0].name][m]) {
                                            dataObj[data1[0].name][m] = new Object();
                                            dataObj[data1[0].name][m][DataFirst[m].name] = new Array();
                                        }
                                    }
                                } else if (n == 3) {
                                    for (var k = 0; k < DataFirst.length; k++) {
                                        if (nodeData[1] == DataFirst[k].id) {
                                            dataObj[data1[0].name][k][DataFirst[k].name].push(oData);
                                        }
                                    }
                                }
                            } else if (nodeData[0] == data1[1].id) {
                                if (n == 2) {
                                    DataSecond.push(oData);
//                                  console.log(DataSecond[0].name);
//                                  for (ra in dataObj[data1[1].name]){
//                                  	console.log( dataObj[data1[1].name][ra])
//                                  }
                                    for (var n = 0; n < DataSecond.length; n++) {
                                    	console.log(DataSecond[n].isParent);
                                    	if( DataSecond[n].isParent == true){
                                    		dataObj[data1[1].name][n] = new Object();
                                    		console.log( dataObj[data1[1].name][n] );
                                        	dataObj[data[1].name][n][DataSecond[n].name] = new Array(); 
                                    	}else{
											var noTh={};
											noTh[DataSecond[n].name]=DataSecond[n];
                                			dataObj[data1[1].name][n] = new Object();
                                			dataObj[data[1].name][n][DataSecond[n].name] = new Array();
//                              			dataObj[data[1].name][n][DataSecond[n].name].push(DataSecond[n].id)
                                    	}
                                       
//                                      console.log(  dataObj[data1[1].name][n].name )
//                                      console.log( dataObj[data[1].name][n][DataSecond[n].name]);
                                        
                                    }
                                } else {
                                    for (var h = 0; h < DataSecond.length; h++) {
                                        if (nodeData[1] == DataSecond[h].id) {
                                            dataObj[data[1].name][h][DataSecond[h].name].push(oData);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // dataObj对象插入左侧导航栏
                var str = "",
                    $el = $("#learnKnow_siderbar_title");
                $el.empty();
                str += '<dt><img src="../images/knowledge_sidebar_icon.png">知识学习</dt>';
                for (var key in dataObj) {
                    str += '<dd><span class="up on"><img src="../images/knowledge_sidebar_up.png"/></span><span class="down"><img src="../images/knowledge_sidebar_down.png"/></span>' + key + '<ul>';
                    for (var i = 0; i < dataObj[key].length; i++) {
                        for (var keys in dataObj[key][i]) {
//                      	console.log(dataObj[key][i][keys])
                        	if(dataObj[key][i][keys].length == 0){
                        		str += '<li class="noThird"';
                        		for( aa in noTh){
                        			
                        			str += 'data-id="'+noTh[aa].id+'" data-paname="'+noTh[aa].treenodeNamePath+'" data-tree="'+noTh[aa].treenodePath+'">' + keys + '<span class="label">&gt;</span>';
                        		}
                        		
                        	}else{
                        		str += '<li>' + keys + '<span class="label">&gt;</span><ol>';
	                            for (var d = 0; d < dataObj[key][i][keys].length; d++) {
	//                               console.log(dataObj[key][i][keys][d].name)
	                            	str += '<li data-id="' + dataObj[key][i][keys][d].id + '" data-paname="' + dataObj[key][i][keys][d].treenodeNamePath + '" data-tree="' + dataObj[key][i][keys][d].treenodePath + '">' + dataObj[key][i][keys][d].name + '</li>';
	                            }
	                            str +="</ol>"
                        	}
                            //console.log(dataObj[key][i][keys].length)
                            str += '</li>';
                        }
                    };
                    str += '</ul></dd>';
                }
                $el.append(str);
            }
            // 左侧菜单栏点击切换；
            $('.knowledgeBtn_knowledge .sidebar dd').has('ul').children('span').click(function(event) {
                $(this).parent('dd').find('ul').slideToggle();
                $(this).toggle();
                $(this).siblings('span').toggle();
            });
            console.log(dataObj,noTh);
            	//	点击二级标题：
//          	$('.knowledgeBtn_knowledge .sidebar dd').find('.noThird').each(function(i,el){
////          		console.log(i,el);
//          		$el.click(function(){
//          			for(var ra in noTh){
//          				rightListFn(noTh[ra], null, 1)
//          			}
//          			return false;
//          		});
//          		return false;
//          	});
            	$('.knowledgeBtn_knowledge .sidebar dd').find('.noThird').click(function(){
            		for(var ra in noTh){
        				rightListFn(noTh[ra].id, null, 1)
        			};
        			var thirdTitlePaName = $(this).attr('data-paname').substr(1, ($(this).attr('data-paname').length - 2)).split('/');
	                var thirdTitleTree = $(this).attr('data-tree').substr(1, ($(this).attr('data-tree').length - 2)).split('/');
	                // 分级标题
	                var str2 = " ",
	                    $el2 = $('#learnKnow_rightCont_titlebar');
	                $el2.empty();
	                // 分级标题数据插入结构中
	                if (thirdTitlePaName) {
	                    for (var b = 0; b < thirdTitlePaName.length; b++) {
	                        str2 += '<span class="on" data-id="' + thirdTitleTree[b] + '">&ensp;' + thirdTitlePaName[b] + '&ensp;&gt;</span>';
	                    }
	                    $el2.html(str2);
	                };
	                 $('#learnKnow_rightCont_titlebar span.on').on('click', function(event) {
		                rightListFn($(this).attr('data-id'), null, 1);
		              	$(this).next().html("");
		                $(this).siblings('span').last().html("");
		//                  $(this).parent().siblings('.botWrap').removeClass('dis').siblings('.botDetail').removeClass('on');
		            });
            	});
                // 点击sidebar 第三级标题
	            $('.knowledgeBtn_knowledge .sidebar dd').has('ol').find('ol').children('li').click(function() {
	                // 第三级标题的id
	                var thirdTitleId = $(this).attr('data-id').toString();
	                // 第三级标题的父级标题
	                var thirdTitlePaName = $(this).attr('data-paname').substr(1, ($(this).attr('data-paname').length - 2)).split('/');
	                var thirdTitleTree = $(this).attr('data-tree').substr(1, ($(this).attr('data-tree').length - 2)).split('/');
	                // 分级标题
	                var str2 = " ",
	                    $el2 = $('#learnKnow_rightCont_titlebar');
	                $el2.empty();
	                // 分级标题数据插入结构中
	                if (thirdTitlePaName) {
	                    for (var b = 0; b < thirdTitlePaName.length; b++) {
	                        str2 += '<span class="on" data-id="' + thirdTitleTree[b] + '">&ensp;' + thirdTitlePaName[b] + '&ensp;&gt;</span>';
	                    }
	                    $el2.html(str2);
	                }
	                rightListFn(thirdTitleId, null, 1);
	                $('#learnKnow_rightCont_titlebar span.on').on('click', function(event) {
		                rightListFn($(this).attr('data-id'), null, 1);
		              	$(this).next().html("");
		                $(this).siblings('span').last().html("");
		//                  $(this).parent().siblings('.botWrap').removeClass('dis').siblings('.botDetail').removeClass('on');
		            });
	            });
//           console.log($('.knowledgeBtn_knowledge .sidebar dd').eq(1).find('ul>li').first().text().slice(0,$('.knowledgeBtn_knowledge .sidebar dd').eq(1).find('ul>li').first().text().length-1));
            
            AddDoneCount();
            var test=window.location.href.trim().split('?')[1];
            if(test == undefined){
            	$("#learnKnow_siderbar_title li[data-id]").eq(0).trigger('click');
//				rightListFn('316294497424680043',null,1)
            }  
        },
        function() {
            console.log("左侧菜单 调用失败");
        },
        function() {
            console.log("左侧菜单 请求完成");
        });
})();

//knowledgebase页面传入数据
(function() {
    if (GetUrlParam("keyword")) {
        var keyWord = GetUrlParam("keyword");
        $('.knowledgeBtn_knowledge .content input[type="text"]').val(keyWord);
        // 分级标题
        var str2 = " ",
            $el2 = $('#learnKnow_rightCont_titlebar');
        $el2.empty();
        // 分级标题数据插入结构中
        str2 += '<span class="on">&ensp;知识搜索&ensp;&gt;&ensp;搜索结果</span>';
        $el2.html(str2);
        rightListFn(null, keyWord, 1);
    }
    // knowledgeBase页面从最新知识/最热知识跳转进入页面数据加载;
    else if (GetUrlParam("id")) {
        var id = GetUrlParam("id");
        var name = GetUrlParam("name")
            // 内页详情
        contListFn(id);
        // 其他知识
        contOtherFn(name);
    } else {
        //rightListFn("20253636275681680031", null, 1);
        // $("#learnKnow_siderbar_title li[data-id]").eq(0).trigger('click');
        // console.log($("#learnKnow_siderbar_title li[data-id]").eq(0));
    }
})();
// 右边列表数据插入
function rightListFn(curId, curName, num) {
    // 判断传入的数据；
    var obj;
    if (curId) {
        obj = {
            kngCategoryId: curId,
            page: num,
            row: 10
        }
    } else if (curName) {
        obj = {
            name: curName,
            page: num,
            row: 10
        }
    } else {
        obj = {
            page: num,
            row: 10
        }
    };
    console.log("传的数据", obj);
    RequestGTMC("listKnowledgeByName", obj,
        function(data) {
            console.log("右侧列表 获取成功");
            console.log(data);
            var str = "",
                $el = $("#learnKnow_botWrap .inner");
            $el.empty();
            if (data.content.length !== 0) {
                for (var i = 0; i < data.content.length; i++) {
                    str += '<li><a data-id="' + data.content[i].id + '">' + data.content[i].title + '</a></li>';
                }
                if (parseInt(data.total) > 1) {
                    console.log(data.total, parseInt(data.total) > 1);
                    var pag = "";
                    for (var i = 1; i <= data.total; i++) {
                        if (data.page === i) {
                            pag += '<a href="javascript:" class="on">' + i + '</a>';
                        } else {
                            // 如果数据过多就显示一至三，总页数前三，当前页数前后两页，共九页
                            if (i < 4 || i > data.total - 3 || (i < data.page + 2 && i > data.page - 2)) {
                                pag += '<a href="javascript:">' + i + '</a>';
                            } else if (i === data.page - 3 || i === data.page + 3) {
                                pag += '<a href="javascript:" class="none">...</a>';
                            }
                        }
                    }
                    $("#common_list_pagination").show().children('.pageBar').html(pag);
                    $("#common_list_pagination .pageBar a").off('click').on('click', function(event) {
                        var pages = $(this).html().trim();
                        if (pages !== "...") {
                            $("#learnKnow_botWrap .inner").prepend('<div class="common_load know"><img src="../images/loading.gif"></div>');
                            rightListFn(curId, curName, pages);
                        }
                    });
                } else {
                    $("#common_list_pagination").removeAttr('style');
                }
            } else {
                str = '<li class="common_none">暂无任何相关记录</li>';
                $("#common_list_pagination").removeAttr('style');
            }
            $el.html(str);
            AddDoneCount();
            $el.parent().removeClass('dis');
            $("#knowKnowledge_botDetail_cont").parent().removeClass('on');
            //右侧内容点击获取详情内页 .inner li 点击切换
            $('.knowledgeBtn_knowledge .inner li a').click(function() {
                $("#knowKnowledge_botDetail_cont").html('<div class="common_load"><img src="../images/loading.gif"></div>');
                // 获取点击的列表元素的id
                var contListId = $(this).attr('data-id');
                var contListTit = $(this).text();
                console.log(contListTit)
                    // 右侧 内容详情页
                contListFn(contListId)
                    // 右侧 其他知识
                contOtherFn(contListTit)
            });
        },
        function() {
            console.log("右侧列表 调用失败");
        },
        function() {
            console.log("右侧列表 请求完成");
        }
    );
}
//右侧内容页 内页详情 数据加载
function contListFn(id) {
    RequestGTMC("getKngInfoById", {
            id: id
        },
        function(data) {
            console.log("内容详情 获取成功");
            console.log(data);
            if (data.length !== 0) {
                var str = "",
                    $el = $("#knowKnowledge_botDetail_cont");
                var str2 = " ",
                    $el2 = $('#learnKnow_rightCont_titlebar');
                $el.empty();
                $el2.empty();
                if (data.treenode_name_path) {
                    var titleData = data.treenode_name_path.substr(1, (data.treenode_name_path.length - 2)).split('/');
                    var treePathId = data.treenode_path.trim().substr(1, data.treenode_path.length - 2).split('/');
                    for (var e = 0; e < titleData.length; e++) {
                        str2 += '<span class="on" data-id="' + treePathId[e] + '">&ensp;' + titleData[e] + '&ensp;&gt;</span>';
                    }
                }
                str2 += '<span>&ensp;' + data.title + '</span>';
                console.log(data.contents == undefined);
                var nowords = "详细内容请下载附件查看";
                str += '<dt>' + data.title + '</dt><dd class="Pcontent">' + (data.contents == undefined ? nowords : data.contents) + '</dd><dd class="ask">你觉得这个知识靠谱吗？</dd><dd class="btns"><input type="button" class="question_KP" value="靠谱"><input type="button" class="question_BKP" value="不靠谱"></dd><dd class="prop"><span class="reason">理由：</span><textarea class="txtBox"></textarea><span class="absolute"> <i class="red">&lowast;&ensp;</i>必填</span><input class="submit" type="button" value="提交" /></dd>';
            }
            $el.append(str);
            dowloadFn(data.id, $el)
            $el2.append(str2);
            $el.parent().addClass('on').siblings('.botWrap').addClass('dis');
            $('table').removeAttr('width');
            $('table').attr('style','width:100%');
            AddDoneCount();
            // 知识评价
            evaluateFn(id);
            // 修改原本的标题事件
            /*$('#learnKnow_rightCont_titlebar').find('span').click(function() {
                if ($(this).is('.on')) {
                    var treePathName = data.treenode_name_path.trim().substr(1, data.treenode_name_path.length - 2).split('/')
                    var treePathId = data.treenode_path.trim().substr(1, data.treenode_name_path.length - 2).split('/');
                    // 分级标题
                    var str2 = " ",
                        $el2 = $('#learnKnow_rightCont_titlebar');
                    $el2.empty();
                    // 分级标题数据插入结构中
                    if (treePathName) {
                        for (var b = 0; b < treePathName.length; b++) {
                            str2 += '<span class="on" data-id="' + treePathId[b] + '">&ensp;' + treePathName[b] + '&ensp;&gt;</span>';
                        }
                        $el2.html(str2);
                    }
                    rightListFn(treePathId[treePathId.length - 1], null, 1);
                    $(this).parent().siblings('.botWrap').removeClass('dis').siblings('.botDetail').removeClass('on');
                }
            });*/
            $('#learnKnow_rightCont_titlebar span.on').on('click', function(event) {
                rightListFn($(this).attr('data-id'), null, 1);
                $(this).next().html("");
                $(this).siblings('span').last().html("");
//                  $(this).parent().siblings('.botWrap').removeClass('dis').siblings('.botDetail').removeClass('on');
            });
        },
        function() {
            console.log("内容详情 调用失败");
        },
        function() {
            console.log("内容详情 请求完成");
        }
    );
}
// 下载附件
function dowloadFn(id, el) {
    RequestGTMC("listUploadBySourceId", {
            sourceId: id
        },
        function(data) {
            console.log("下载附件 获取成功");
            console.log(data);
            var str, $el;
            $el = el.find('.Pcontent');
            if (data.length !== 0) {
                for (var i = 0; i < data.length; i++) {
                    str = '<div class="detail_dowloadBox">下载附件：<a href="' + ITSMLINK + 'fileDownload?filepath=' + data[i].path + '" class="detail_dowloadBtn">' + data[i].name + '<a/></div>';
                }
            }
            $el.after(str);
        },
        function() {
            console.log("下载附件  调用失败");
        },
        function() {
            console.log("下载附件  请求完成");
        }
    );
};
// 其他知识 数据获取函数
function contOtherFn(name) {
    RequestGTMC("listKnowledgeByName", {
            name: name || null,
            page: 1
        },
        function(data) {
            console.log("其他知识 获取成功");
            console.log(data);
            if (data.length !== 0) {
                var str = "",
                    $el = $("#knowKnowledge_botDetail_other");
                $el.empty();
                str += '<dt>浏览本知识的人也看了</dt>';
                for (var w = 1; w < data.length; w++) {
                    str += '<dd data-id="' + data[w].id + '">&lowast;&ensp;&ensp;<span>' + data[w].title + '</span></dd>';
                }
            }
            $el.append(str);
            $el.parent().addClass('on').siblings('.botWrap').addClass('dis');
            AddDoneCount();
            $("#knowKnowledge_botDetail_other").find('dd').click(function() {
                contListFn($(this).attr('data-id'));
            });
        },
        function() {
            console.log("其他知识 调用失败");
        },
        function() {
            console.log("其他知识 请求完成");
        }
    );
}
// 评价部分 数据函数
function evaluateFn(thisId) {
    var strings;
    var contents;
    console.log(strings)
    thisId = thisId || null;
    // 好评状态变量
    var flagK = true;
    // 差评状态变量
    var flagB = true;
    $('.knowledgeBtn_knowledge .btns>input').click(function(el) {
        // 点击的目标对象
        $target = $(el.target)
        if ($target.is('.question_BKP')) {
            if (flagB) {
                $(this).addClass('on').siblings('input').removeClass('on');
                $(this).parent().siblings('.prop').addClass('on');
                flagK = true;
                // 点击提交关闭弹框
                $('.knowledgeBtn_knowledge .prop .submit').click(function() {
                    if ($(this).siblings('.txtBox').val() == '') {
                        confirm('请告诉我们哪儿做的不好，我们将不断改进！')
                    } else {
                        strings = '差评';
                        // 填写差评理由
                        $(this).parent('.prop').removeClass('on');
                        contents = $('.knowledgeBtn_knowledge .prop .txtBox').val();
                        // 调用评价接口
                        $(this).parent().siblings('.btns').children('.question_BKP').addClass('report_wait');
                        evafn(thisId, strings, contents);
                        $(this).parents('dl').children('.btns').children('input').off('click');
                    }
                })
            } else {
                // 再次点击取消评价
                $(this).removeClass('on');
                $(this).parent().siblings('.prop').removeClass('on');
                strings = '';
            }
            flagB = !flagB;
        } else if ($target.is('.question_KP')) {
            if (flagK) {
                $(this).addClass('on').siblings('input').removeClass('on');
                $(this).parent().siblings('.prop').removeClass('on');
                flagB = true;
                strings = '好评';
                // 调用评价接口
                $(this).addClass('report_wait');
                evafn(thisId, strings, null);
                $(this).parents('dl').children('.btns').children('input').off('click');
            } else {
                // 再次点击取消评价
                $(this).removeClass('on');
                strings = '';
            }
            flagK = !flagK;
        };
    })
}
// 评价加载函数
function evafn(id, str, content) {
    console.log("评价传入参数" + id, str, content)
    RequestGTMC("kngCommentSubmit", {
                kngId: id,
                comment_type: str,
                content: content || null
            },
            function(data) {
                console.log("知识评价 获取成功");
                console.log(data);
                if (data.length !== 0) {
                    console.log(data.msg, data.success, data.data)
                }
                $(".report_wait").removeClass('report_wait').addClass('report_over');
                AddDoneCount();
            },
            function() {
                console.log("知识评价 调用失败");
            },
            function() {
            console.log("知识评价 请求完成");
        }
    );
}